//
//  WOPInstanceFactory.m
//  AtWork2
//
//  Created by lingen on 2020/2/4.
//  Copyright © 2020 Foreverht. All rights reserved.
//

#import "WOPInstanceFactory.h"
#import <objc/runtime.h>

static NSString* DEFAULT_INSTANCE_NAME = @"__WOP_DEFAULT_NAME";
@interface WOPInstanceFactory()

@property (nonatomic,strong) NSMutableDictionary* dics;

@end

@implementation WOPInstanceFactory

+(instancetype)sharedInstance{
    static WOPInstanceFactory* instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[WOPInstanceFactory alloc] init];
        instance.dics = [[NSMutableDictionary alloc] init];
    });
    return instance;
}

/**
 * 注册一个实现
 **/
-(void)registerInstance:(id)instance for:(Protocol*)protocol{
    [self registerInstance:instance for:protocol withName:DEFAULT_INSTANCE_NAME];
}

/**
 * 注册一个实现,并标明t自己实现的名字
 **/
-(void)registerInstance:(id)instance for:(Protocol*)protocol withName:(NSString*)name{
    NSString* key = [NSString stringWithFormat:@"%@%@",[self protocolName:protocol],name];
    _dics[key] = instance;
}

/**
 * 获取一个实现
 **/
-(id)getInstance:(Protocol*)protocol{
    return [self getInstance:protocol withName:DEFAULT_INSTANCE_NAME];
}

-(id)getInstance:(Protocol *)protocol withName:(NSString*)name{
    NSString* key = [NSString stringWithFormat:@"%@%@",[self protocolName:protocol],name];
    return _dics[key];
}
/**
 * 是否有注入实现
 **/
-(BOOL)hasInstance:(Protocol*)protocol{
    return [self hasInstance:protocol withName:DEFAULT_INSTANCE_NAME];
}

-(BOOL)hasInstance:(Protocol*)protocol withName:(NSString*)name{
    NSString* key = [NSString stringWithFormat:@"%@%@",[self protocolName:protocol],name];
    if ([_dics.allKeys containsObject:key]) {
        return YES;
    }
    return NO;
}


-(NSString*)protocolName:(Protocol*)protocol{
    return [NSString stringWithUTF8String:protocol_getName(protocol)];
}
@end
